package com.xm.share.web.intercepter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.xm.share.common.config.Constants;
import com.xm.share.common.config.SystemConfig;

public class AuthIntercepter implements HandlerInterceptor {

	private static final Logger LOGGER = LoggerFactory.getLogger(AuthIntercepter.class);

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		LOGGER.info("检查当前页面是否已经登陆");
		String requestURI = request.getRequestURI();
		if (!SystemConfig.getNoAuthUrl().contains(requestURI)) {
			Object object = request.getSession().getAttribute(Constants.USER_ID);
			if (object == null) {
				if (isAjax(request)) {
					response.setHeader("sessionstatus", "timeout");// 在响应头设置session状态
					return false;
				}
				response.sendRedirect(request.getContextPath() + "/login");
			}
		}
		return true;
	}

	private boolean isAjax(HttpServletRequest request) {
		return (request.getHeader("X-Requested-With") != null
				&& "XMLHttpRequest".equals(request.getHeader("X-Requested-With").toString()));
	}

	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
	}

}